import { ApiFail } from '@common/utils';
import { HZMJService } from './hzmj.service';
import { CMMJService } from './cmmj.service';
import { RedisService } from '@common/reids/redis.service';
import { defaultConfig } from '@game/config/config';
import { checkHu } from './checkHu';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class MjService {
  logger: Logger;

  constructor(
    public readonly hzmjService: HZMJService,
    public readonly cmmjService: CMMJService,
    public readonly redisService: RedisService,
  ) {
    this.logger = new Logger('MJService');
  }
  async chupaiAction(body: any) {
    console.log('chupaiAction:');

    const { userId, pai, roomId } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      try {
        if (game.model == 1) {
          await this.cmmjService.chuPai(game, userId, pai);
        } else if (game.model == 2) {
          await this.hzmjService.chuPai(game, userId, pai);
        }
        // 一局
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        return true;
      } catch (error) {
        console.log(error);
      }
    }
  }
  async chiAction(body: any) {
    console.log('chiAction:');

    const { userId, roomId, index = undefined } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      try {
        if (game.model == 1) {
          await this.cmmjService.dochi(game, userId, index);
        }
      } catch (error) {
        console.log(error);
      }
      // 一局
      await this.redisService.hset({
        key: 'game' + roomId,
        value: { ...game },
        expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
      });
      return '在游戏！！！';
    }
  }

  async pengAction(body: any) {
    console.log('pengiAction:');
    const { userId, roomId } = body;
    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
     let result =false
      try {
        if (game.model == 1) {
          result=  await this.cmmjService.peng(game, userId);
        } else if (game.model == 2) {
           await this.hzmjService.peng(game, userId);
        }
        // 一局
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        console.log('pengiAction:完成');

        return result;
      } catch (error) {
        console.log(error);
      }
    }
  }

  async gangAction(body: any) {
    console.log('gangAction:');

    const { userId, pai, buzhang, roomId } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      let result =false

      try {
        if (game.model == 1) {
          result=   await this.cmmjService.gang(game, userId, pai, buzhang);
        } else if (game.model == 2) {
          await this.hzmjService.gang(game, userId, pai);
        }
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        console.log('gangAction:完成');

        return result;
      } catch (error) {
        console.log(error);
      }
    }
  }
  async huAction(body: any) {
    console.log('huAction:');

    const { userId, pais=null, roomId } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      let result =false

      try {
        if (game.model == 1) {
          result=  await this.cmmjService.hu(game, userId,pais);
        } else if (game.model == 2) {
          await this.hzmjService.hu(game, userId);
        }
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        console.log('huAction:完成');

        return result;
      } catch (error) {
        console.log(error);
      }
    }
  }
  async guoAction(body: any) {
    console.log('guoAction:');

    const { userId, pai, roomId } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      let result =false

      try {
        if (game.model == 1) {
          result=  await this.cmmjService.guo(game, userId);
        } else if (game.model == 2) {
          await this.hzmjService.guo(game, userId);
        }
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        console.log('guoAction:完成');

        return result;
      } catch (error) {
        console.log(error);
      }
    }
  }
  async autoChupaiAction(body: any) {
    console.log('autoChupaiAction:');
    const { userId, roomId } = body;
    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      // 听牌不碰牌 只杠 或者过 ，碰牌 打牌要检查听牌可能
      let seats = game.gameSeats.find((item) => item.userId == userId);
      // 检测是否糊了
      if (seats.canHu) {
        return;
      }
      if (seats.canChuPai == false) {
        return;
      }
      checkHu.sort(seats.holds.slice(0));
      console.log('未出牌:', checkHu.getName(seats.holds).toString());

      // 听不了的情况下  分析法打  有可能听的情况 要优先
      let maybe = -1;
      for (var m = 0; m < seats.holds.length; m++) {
        var temp = [].concat(seats.holds);
        temp.splice(m, 1);
        let map = checkHu.doCheckTing(temp, [31], game.isCsJiang); //检查平胡
        if (map.length > 0) {
          map = map.concat([31]);
          console.log('打了听牌：', checkHu.getName(map).toString());
          maybe = seats.holds[m];
          break;
        }
      }
      if (maybe != undefined && maybe != -1) {
        try {
          console.log('机器出牌', checkHu.getName([maybe]));

          if (game.model == 1) {
            await this.cmmjService.chuPai(game, userId, maybe);
          } else if (game.model == 2) {
            await this.hzmjService.chuPai(game, userId, maybe);
          }
          await this.redisService.hset({
            key: 'game' + roomId,
            value: { ...game },
            expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
          });
        } catch (error) {
          console.log(error);
        }
        return true;
      }

      let map2 = checkHu.doAutoChuPai(seats.holds, [31]); //检查平胡
      let keys = Object.keys(map2);

      checkHu.sortDesc(keys);

      console.log(keys);

      console.log(
        '最适合出的牌',
        checkHu.getName(keys.map((key) => map2[key])),
      );
      console.log(userId, seats.canChuPai, checkHu.getName([map2[keys[0]]]));
      try {
        if (game.model == 1) {
          await this.cmmjService.chuPai(game, userId, map2[keys[0]]);
        } else if (game.model == 2) {
          await this.hzmjService.chuPai(game, userId, map2[keys[0]]);
        }
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        let newholds = [];
        for (let index = 0; index < seats.holds.length; index++) {
          if (seats.holds[index] == map2[keys[0]]) {
            seats.holds.splice(index, 1);
            break;
          }
        }
        newholds = seats.holds;
        console.log('手牌：', checkHu.getName(newholds).toString());
        let map = checkHu.doCheckTing(newholds, [31], game.isCsJiang); //检查平胡
        if (map.length > 0) {
          map = map.concat([31]);
          console.log('听牌：', checkHu.getName(map).toString());
        }
      } catch (error) {
        console.log(error);
      }
    }
    return '在游戏！！！';
  }

  async qishouAction(body: any){
    const { userId, pai, roomId,qishou,message } = body;

    let game: any = await this.redisService.hget('game' + roomId);
    if (!game) {
      console.log('不存在游戏数据！！！');
      throw new ApiFail(600, '不存在游戏数据！！！');
    } else {
      //
      try {
        if (game.model == 1) {
          await this.cmmjService.qishou_notify(game, userId,qishou,message);
        }
        await this.redisService.hset({
          key: 'game' + roomId,
          value: { ...game },
          expire: defaultConfig.scoreCacheTime , // 3秒  为了就是瞬时刷新过快 导致的mysql问题
        });
        console.log('qishouAction:完成');

        return true;
      } catch (error) {
        console.log(error);
      }
    }
  }
}
